package com.ts.filesystem.service;

import com.alibaba.fastjson.JSON;
import com.ts.filesystem.dao.FileSystemRepository;
import com.ts.framework.domain.filesystem.FileSystem;
import com.ts.framework.domain.filesystem.response.FileSystemCode;
import com.ts.framework.domain.filesystem.response.UploadFileResult;
import com.ts.framework.exception.ExceptionCast;
import com.ts.framework.model.response.CommonCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * 文件管理业务层
 */
@Service
@Slf4j
public class FileSystemService {
    @Autowired
    FileSystemRepository fileSystemRepository;

    @Value("${ts.fastdfs.tracker_servers}")
    private String tracker_servers;
    @Value("${ts.fastdfs.charset}")
    private String charset;
    @Value("${ts.fastdfs.connect_timeout_in_seconds}")
    private int connect_timeout_in_seconds;
    @Value("${ts.fastdfs.network_timeout_in_seconds}")
    private int network_timeout_in_seconds;


    //文件上传
    public UploadFileResult uploadFile(MultipartFile multipartFile, String filetag, String businesskey, String metadata) {
        //上传文件到fastDFS
        if (multipartFile == null) {
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
        }
        String file_id = this.uploadFastDFS(multipartFile);
        if (StringUtils.isEmpty(file_id)) {
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_SERVERFAIL);
        }
        //文件保存mongoDB
        FileSystem fileSystem = new FileSystem();
        //文件id
        fileSystem.setFileId(file_id);
        //文件系统路径
        fileSystem.setFilePath(file_id);
        //业务标识
        fileSystem.setBusinesskey(businesskey);
        //文件标签
        fileSystem.setFiletag(filetag);
        //文件名
        fileSystem.setFileName(multipartFile.getOriginalFilename());
        //大小
        fileSystem.setFileSize(multipartFile.getSize());
        //文件类型
        fileSystem.setFileType(multipartFile.getContentType());
        //元数据
        if (StringUtils.isNotEmpty(metadata)) {
            Map map = JSON.parseObject(metadata, Map.class);
            fileSystem.setMetadata(map);
        }
        return new UploadFileResult(CommonCode.SUCCESS, fileSystem);
    }

    //上传文件到fastDFS 返回文件id
    private String uploadFastDFS(MultipartFile multipartFile) {
        try {
            this.initFastDFSConfig();
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
            byte[] bytes = multipartFile.getBytes();
            //获取文件名
            String originalFilename = multipartFile.getOriginalFilename();
            //截取后缀扩展名
            String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String file_id = storageClient1.upload_file1(bytes, ext, null);
            return file_id;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    //初始化fastDFS配置
    private void initFastDFSConfig() {
        try {
            ClientGlobal.initByTrackers(tracker_servers);
            ClientGlobal.setG_charset(charset);
            ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);
            ClientGlobal.setG_network_timeout(network_timeout_in_seconds);
        } catch (IOException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } catch (MyException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

}
